﻿' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2009
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.IO
Imports Boogaloo.Core
Imports Boogaloo.Core.BLL
Imports Boogaloo.Core.UI
Imports Boogaloo.Admin.UI.Controls

Namespace UI.Webpages

    Partial Public Class FileManager
        Inherits BaseAdminPage



        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Try
                If Not String.IsNullOrEmpty(Request.QueryString("dir")) Then upload_directory = Request.QueryString("dir")
                If Not upload_directory.EndsWith("/") Then upload_directory &= "/"
                Dim path As String = Server.MapPath("~" & upload_directory)

            Catch ex As Exception
                upload_directory = root_dir
            End Try


            If Not Page.IsPostBack Then

                Dim dirs As String() = Groove.GetFullDirectoryTree(Server.MapPath("~" & root_dir))
                Dim dirName As String = String.Empty
                For Each dirName In dirs
                    ddl_directory.Items.Add(New ListItem(Groove.RewriteServerPathAsVirtualPath(dirName)))
                Next
                ddl_directory.SelectedValue = upload_directory
                ddl_directory.Attributes.Add("onchange", "window.location='FileManager.aspx?dir=' + this[this.selectedIndex].value")

                lit_current_dir.Text = String.Format("<span class=""current directory"">{0}</span>", upload_directory)


                dir_files = Directory.GetFiles(Server.MapPath("~" & ddl_directory.SelectedValue))

                BindPage()

            End If

        End Sub

        Private Sub BindPage()

            rpt_files.DataSource = dir_files
            rpt_files.DataBind()

            If dir_files.Count Or String.Equals(upload_directory, root_dir) Then dwiz_dir.Visible = False

        End Sub

        Private Sub rpt_files_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_files.ItemDataBound

            Dim file_name As String = CType(e.Item.DataItem, String)
            If Not String.IsNullOrEmpty(file_name) Then

                Dim info As New FileInfo(file_name)

                If info IsNot Nothing Then

                    Dim lht As LabelHiddenTextbox = CType(e.Item.FindControl("lht_filename"), LabelHiddenTextbox)
                    lht.label = info.Name
                    lht.Text = info.Name
                    lht.CommandArgument = info.Name

                    Dim imgext As New ArrayList
                    imgext.Add(".jpg")
                    imgext.Add(".png")
                    imgext.Add(".gif")

                    Dim hyp As HyperLink = CType(e.Item.FindControl("hyp"), HyperLink)
                    Dim img As New Image
                    If imgext.Contains(info.Extension.ToLower) Then
                        img.ImageUrl = String.Format("~{0}{1}", upload_directory, info.Name)
                        img.AlternateText = info.Name
                        img.Width = 50
                        hyp.Controls.Add(img)
                        hyp.Target = "_blank"
                        hyp.NavigateUrl = img.ImageUrl
                    Else
                        hyp.Visible = False
                    End If


                    Dim dwiz As CommitWizard = CType(e.Item.FindControl("dwiz"), CommitWizard)
                    dwiz.CommandArgument = file_name



                End If


            End If

        End Sub

        Protected Sub lb_add_dir_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_add_dir.Click

            If Page.IsValid Then

                Dim new_folder_name As String = Node.UrlRewriteVirtualPathEncoder(txt_dir_name.Text).Replace("-", String.Empty)
                Dim dirName As String = Server.MapPath("~" & upload_directory) & new_folder_name

                Try
                    Directory.CreateDirectory(dirName)

                    If Not dirName.EndsWith("/") Then dirName &= "/"
                    Response.Redirect(String.Format("FileManager.aspx?dir={0}{1}", upload_directory, new_folder_name))

                Catch ex As Exception

                End Try

                Groove.RefreshPage()

            End If

        End Sub

        Protected Sub lb_upload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_upload.Click

            If Page.IsValid And up_file.HasFile Then
                Dim found As Boolean = False
                Dim check As String = String.Empty
                For Each check In allowed_file_types
                    If up_file.FileName.ToLower.EndsWith(check.ToLower) Then
                        found = True
                        Exit For
                    End If
                Next
                If found Then up_file.SaveAs(Server.MapPath(upload_directory & up_file.FileName))
                Groove.RefreshPage()
            End If

        End Sub

        Protected Sub dwiz_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim dwiz As CommitWizard = CType(sender, CommitWizard)
            Dim file_name As String = dwiz.CommandArgument

            File.Delete(file_name)
            BindPage()

        End Sub

        Protected Sub dwiz_dir_Click(ByVal sender As Object, ByVal e As EventArgs) Handles dwiz_dir.Click

            If Page.IsValid Then

                Dim path As String = Server.MapPath("~" & upload_directory)
                If Directory.GetDirectories(path).Count = 0 And Directory.GetFiles(path).Count = 0 Then Directory.Delete(path)

                Response.Redirect("FileManager.aspx")

            End If

        End Sub


        Protected Sub lht_Click(ByVal sender As Object, ByVal e As EventArgs)

            If Page.IsValid Then
                Dim lht As LabelHiddenTextbox = CType(sender, LabelHiddenTextbox)
                Dim info As FileInfo = Nothing
                Try
                    info = New FileInfo(Server.MapPath("~" & ddl_directory.SelectedValue) & lht.CommandArgument)
                Catch ex As Exception
                    info = Nothing
                End Try

                If info.Exists Then
                    File.Move(info.FullName, Server.MapPath("~" & upload_directory & lht.Text))
                End If

            End If

            BindPage()

        End Sub


        Private root_dir As String = "/uploads/"

        Private _allowed As ArrayList = Nothing
        Public ReadOnly Property allowed_file_types() As ArrayList
            Get
                If _allowed Is Nothing Then
                    _allowed = New ArrayList
                    Dim types As String() = CoreSettings.GetSetting("FILEMANAGER_FileTypes").Split(",")
                    Dim t As String = String.Empty
                    For Each t In types
                        _allowed.Add(t)
                    Next
                End If
                Return _allowed
            End Get
        End Property

        Private _upload_directory As String = root_dir
        Public Property upload_directory() As String
            Get
                Return _upload_directory
            End Get
            Set(ByVal value As String)
                _upload_directory = value
            End Set
        End Property

        Private _dir_files As String()
        Public Property dir_files() As String()
            Get
                Return _dir_files
            End Get
            Set(ByVal value As String())
                _dir_files = value
            End Set
        End Property



    End Class

End Namespace